//
//  WNSearchVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/6.
//

import UIKit

private let SearchHeader = "SearchHeaderView"

class WNSearchVC: WNBaseVC {
    
    lazy var searchView: WNSearchView = {
        let view = WNSearchView()
        view.searchType(2)
        view.searchClosure = { [weak self] str in
            self?.searchRequest(str)
        }
        view.btnClosure = {[weak self] in
            self?.dismiss(animated: true)
        }
        return view
    }()
    
    lazy var searchTabView: WNTableView = {
        let view = WNTableView()
        view.delegate = self
        view.dataSource = self
        view.rowHeight = 44
        view.sectionHeaderHeight = 36
        view.register(SearchTerndyCell.self, forCellReuseIdentifier: SearchTerndyCell.identifier)
        view.register(SearchHistoryCell.self, forCellReuseIdentifier: SearchHistoryCell.identifier)
        return view
    }()
    
    lazy var resultColView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: ScreenW, height: scaleWidth(116) + 24)
        let col = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .white
        col.delegate = self
        col.dataSource = self
        col.register(SearchResultColCell.self, forCellWithReuseIdentifier: SearchResultColCell.identifier)
        col.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .search, imageStr: .common, tapBlock: { [weak self] in
            col.mj_header?.beginRefreshing()
        })
        col.isHidden = true
        return col
    }()
    
    var terndyArr = [String]()
    
    var resultArr = [BookDetailModel]()
    
    var searchStr = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(searchView)
        view.addSubview(searchTabView)
        view.addSubview(resultColView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(StatusBarHeight)
            make.left.right.equalTo(0)
            make.height.equalTo(44)
        }
        searchTabView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom).offset(0)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarMargin)
        }
        resultColView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom).offset(0)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarMargin)
        }
    }
    
    override func dataConfig() {
        pageName = "Search"
        listSettingRefresh()
        getTerndyRequest()
    }
}

extension WNSearchVC {
    
    func listSettingRefresh() {
        resultColView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.page = 1
            self?.hasPage = false
            self?.searchRequest(self?.searchStr ?? "")
        })
        
        resultColView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if self?.page == 1 && (self?.resultArr.count ?? 0) == 0 {
                self?.resultColView.mj_footer?.endRefreshing()
                return
            }
            if self?.hasPage == true {
                self?.page += 1
                self?.searchRequest(self?.searchStr ?? "")
            }else {
                self?.resultColView.mj_footer?.endRefreshingWithNoMoreData()
            }
        })
    }
    
    func reloadView() {
        searchTabView.reloadData()
    }
}

extension WNSearchVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int { 2 }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? terndyArr.count : getHistory().count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: SearchTerndyCell.identifier, for: indexPath) as! SearchTerndyCell
            cell.model = terndyArr[indexPath.item]
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: SearchHistoryCell.identifier, for: indexPath) as! SearchHistoryCell
            cell.model = getHistory()[indexPath.item]
            cell.lineView.isHidden = indexPath.item == (getHistory().count - 1)
            cell.deleteClosure = { [weak self] in
                deleteHistory(indexPath.row)
                self?.reloadView()
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let str = indexPath.section == 0 ? terndyArr[indexPath.item] : getHistory()[indexPath.item]
        searchRequest(str)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = SearchTtitleView()
        view.setTitleType(section)
        view.isHidden = (section == 0 ? terndyArr.isEmpty : getHistory().isEmpty)
        view.deleteClosure = { [weak self] in
            clearHistory()
            self?.reloadView()
        }
        return view
    }
}

extension WNSearchVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        resultArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SearchResultColCell.identifier, for: indexPath) as! SearchResultColCell
        cell.model = resultArr[indexPath.item]
        cell.lineView.isHidden = indexPath.item == (resultArr.count - 1)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        wn_pushBookVC(resultArr[indexPath.item].bookId ?? "")
    }
}

extension WNSearchVC {
    
    func getTerndyRequest() {
        provider_discover.rx.request(.hotWord)
            .asObservable().mapModel(BaseModel<[String]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                if let words = model.data {
                    self?.terndyArr = words
                    self?.reloadView()
                }else {
                    self?.wn_toast(model.msg ?? "")
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
    
    func searchRequest(_ str: String) {
        searchStr = str
        addHistory(str)
        reloadView()
        searchTabView.isHidden = true
        if page == 1 {
            WNBuriedManager.shared.search(str)
        }
        provider_discover.rx.request(.search(str, page))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.resultColView.isHidden = false
                self?.resultColView.ly_emptyView.imageStr = EmptyImage.common.rawValue
                self?.resultColView.ly_emptyView.detailStr = EmptyDesc.search.rawValue
                self?.resultColView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.resultColView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.resultColView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.resultColView.ly_emptyView.btnTitleStr = "點擊刷新"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.resultColView.mj_header?.endRefreshing()
                    self?.resultColView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.resultArr.removeAll()
                    self?.resultColView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 9
                    self?.resultArr += arr
                }else {
                    self?.resultColView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.resultColView.reloadData()
                self?.resultColView.mj_header?.endRefreshing()
                self?.resultColView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
                self?.resultColView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.resultColView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.resultColView.ly_emptyView.btnTitleStr = "點擊刷新"
                self?.resultColView.mj_header?.endRefreshing()
                self?.resultColView.mj_footer?.endRefreshing()
                self?.resultColView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
}
